package com.zf.yichat.service.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Component
@Slf4j
public class RongCloudApplication {

    // 融云-聊天室通讯地址
    public static final String CHAT_ROOM_URL = "http://api-cn.ronghub.com/";

    @Value("${rongcloud.key}")
    private String RONGCLOUD_KEY;

    @Value("${rongcloud.secret}")
    private String RONGCLOUD_SECRET;



    /**
     * 融云-聊天室功能通讯构造器
     * @return
     * @throws Exception
     */
    public HttpPost imConstructor(String reqUrl) throws Exception {

        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(CHAT_ROOM_URL + reqUrl + ".json");

        // 重置随机数种子。
        Random random = new Random(System.currentTimeMillis());

        int nonce = random.nextInt(); // 获取随机数。
        long timestamp = System.currentTimeMillis(); // 获取时间戳（毫秒）。

        String signature = sha1(RONGCLOUD_SECRET + nonce + timestamp);
        System.out.println("nonce: " + nonce);
        System.out.println("timestamp: " + timestamp);
        System.out.println("signature: " + signature);

        // 设置请求头参数
        httpPost.setHeader("App-Key", RONGCLOUD_KEY);
        httpPost.setHeader("Nonce", String.valueOf(nonce));
        httpPost.setHeader("Timestamp", String.valueOf(timestamp));
        httpPost.setHeader("Signature", signature);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        return httpPost;
    }


    /**
     * 执行请求
     * @param httpPost
     * @return
     * @throws IOException
     */
    public String executeReq(HttpPost httpPost) {

        String response = "";

        // 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 执行请求并获取响应
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // 解析响应数据
            response = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
            System.out.println("response: " + response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭 HttpClient 实例
            HttpClientUtils.closeQuietly(httpClient);
        }
        return response;
    }

    public FsResponse judgmentResults(String response){
        // 解析响应数据

        JSONObject jsonObject = JSON.parseObject(response);
        String code = jsonObject.getString("code");

        if ("200".equals(code)) {
            return FsResponseGen.successData(response);
        }else {
            String errorMessage = jsonObject.getString("errorMessage");
            return FsResponseGen.failMsg(errorMessage);
        }
    }

    public static void main(String[] args) throws Exception {

        // 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost("http://api-cn.ronghub.com/chatroom/keepalive/add.json");

        // 重置随机数种子。
        Random random = new Random(System.currentTimeMillis());

        int nonce = random.nextInt(); // 获取随机数。
        long timestamp = System.currentTimeMillis(); // 获取时间戳（毫秒）。

        String signature = "hPOxgcd2E9" + nonce + timestamp;
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] digest = md.digest(signature.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        signature = sb.toString();

        System.out.println("nonce: " + nonce);
        System.out.println("timestamp: " + timestamp);
        System.out.println("signature: " + signature);

        // 设置请求头参数
        httpPost.setHeader("App-Key", "c9kqb3rdcjazj");
        httpPost.setHeader("Nonce", String.valueOf(nonce));
        httpPost.setHeader("Timestamp", String.valueOf(timestamp));
        httpPost.setHeader("Signature", signature);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // 设置请求消息体参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("chatroomId", "3ed9c60e-1913-4727-837b-a8c7c1a6d2aa"));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

        // 执行请求并获取响应
        HttpResponse httpResponse = httpClient.execute(httpPost);

        // 解析响应数据
        String response = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        System.out.println("response: " + response);

        // 关闭 HttpClient 实例
        httpClient.close();
    }


    public String sha1(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] digest = md.digest(input.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
